package master.proyectoweb.managedbeans;

import master.proyectoweb.entities.User;
import master.proyectoweb.managedbeans.util.JsfUtil;
import master.proyectoweb.managedbeans.util.PaginationHelper;
import master.proyectoweb.ejb.UserFacade;

import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityExistsException;

@Named("userController")
@RequestScoped
public class UserController implements Serializable {

    private FacesContext context;
    private User current;
    private DataModel items = null;
    @EJB
    private master.proyectoweb.ejb.UserFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private boolean renderMyData;
    private boolean renderMyOrders;
    private boolean renderAdmins;

    public UserController() {
        context = FacesContext.getCurrentInstance();
        current = (User)context.getExternalContext().getSessionMap().get("currentUser");
        
    }

    public User getSelected() {
        if (current == null) {
            current = new User();
            selectedItemIndex = -1;
        }
        return current;
    }

    private UserFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }
    
    public String checkLogin() {
        String res = "access";     
        User user = getFacade().findByEmailAndPassword(current.getEmail(), current.getPassword());
        if(user == null){
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/resources/webtext").getString("user_incorrect"));
        }
        else{
            context.getExternalContext().getSessionMap().put("currentUser", user);
            if(user.getType().equals("customer")){
                res = prepareMyCustomerData();
            }            
            else{
                res = prepareMyAdminData();
            }
        }      
        return res;
    }
    
    public String checkRegister() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/webtext").getString("userCreated"));
        }
        catch(EntityExistsException e){
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/webtext").getString("register_error"));
        }
        catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/webtext").getString("PersistenceErrorOccured"));
        }
        
        return "access";
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (User) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new User();
        selectedItemIndex = -1;
        return "access";
    }
    
    public String prepareAccess() {
        String res;
        selectedItemIndex = -1;
               
        current = (User)context.getExternalContext().getSessionMap().get("currentUser");
        
        if(current == null){
            res = "access";
        }
        else if(current.getType().equals("customer")){
            res = prepareMyCustomerData();
        }
        else {
            res = "admin_page";
        }
        
        return res;
    }
    
    public String prepareMyCustomerData(){
        renderMyData = true;
        renderMyOrders = false;
        current = (User)context.getExternalContext().getSessionMap().get("currentUser");
        return "customer_page";
    }
    
    public String prepareMyAdminData(){
        renderMyData = true;
        current = (User)context.getExternalContext().getSessionMap().get("currentUser");
        return "admin_page";
    }
    
    public String prepareMyOrders(){
        renderMyData = false;
        renderMyOrders = true;
        return "customer_page";
    }
    
    public String prepareAdminList() {
        return "admin_page";
    }
    
    
    
    public String logout(){
        context.getExternalContext().invalidateSession();
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/webtext").getString("logout_message"));
        
        return "index";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("UserCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (User) getItems().getRowData();
        current = (User) context.getExternalContext().getSessionMap().get("currentUser");
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "customer_page";
    }

    public String update() {
        String res;
        User user = getFacade().editUser(current);
            
        if(user != null){
             context.getExternalContext().getSessionMap().put("currentUser", current);
             JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/webtext").getString("user_updated"));
             res = prepareMyCustomerData();
        }
        else{
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/resources/webtext").getString("PersistenceErrorOccured"));
            res = null;
        }
        
        return res;
    }

    public String destroy() {
        current = (User) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("UserDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public User getUser(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public boolean isRenderMyData() {
        return renderMyData;
    }

    public boolean isRenderMyOrders() {
        return renderMyOrders;
    }  

    public boolean isRenderAdmins() {
        return renderAdmins;
    }
    
    

    
    
    
    @FacesConverter(forClass = User.class)
    public static class UserControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UserController controller = (UserController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "userController");
            return controller.getUser(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof User) {
                User o = (User) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + User.class.getName());
            }
        }

    }

}
